/*
 * Copyright (c) 2011-2022, baomidou (jobob@qq.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.sagacity.framework.jdbc.mybatis.meta;


import com.sagacity.framework.annotation.TableId;
import com.sagacity.framework.annotation.TableLogic;
import com.sagacity.framework.util.StringUtil;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.ToString;

import java.io.Serializable;
import java.lang.reflect.Field;

/**
 * 数据库表字段反射信息
 *
 * @author hubin sjy willenfoo tantan
 * @since 2016-09-09
 */
@Getter
@ToString
@EqualsAndHashCode
@SuppressWarnings("serial")
public class TableFieldInfo implements Serializable {

    /**
     * 属性
     *
     * @since 3.3.1
     */
    private final Field field;
    /**
     * 字段名
     */
    private final String column;
    /**
     * 属性名
     */
    private final String property;

    /**
     * 属性是否是 CharSequence 类型
     */
    private final boolean isCharSequence;

    /**
     * 是否主键字段
     */
    private final boolean isPrimaryKey;

    /**
     * 是否主键字段
     */
    private final boolean isLogicDelete;



    /**
     * 全新的 存在 TableField 注解时使用的构造函数
     */
    public TableFieldInfo(Field field) {
        field.setAccessible(true);
        this.field = field;
        this.property = field.getName();
        this.column = StringUtil.toUnderlineCase(field.getName());
        this.isCharSequence = CharSequence.class.isAssignableFrom(field.getType());
        this.isPrimaryKey = isPrimaryKey(field);
        this.isLogicDelete = isLogicDelete(field);
    }

    private boolean isLogicDelete(Field field) {
        TableLogic logic = field.getAnnotation(TableLogic.class);
        return logic != null;
    }

    /**
     * 是否主键字段，有注解@TableId则是主键，没有注解则默认id字段是主键
     * @param field 字段
     * @return 是否主键
     */
    private boolean isPrimaryKey(Field field) {
        TableId tableId = field.getAnnotation(TableId.class);
        if(tableId != null){
            return true;
        }else{
            return field.getName().equals("id");
        }
    }


}
